<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>WebSocket Chat</title>
  <style>
  .chat {
  width: 80%;
  height: 200px;
  border: 1px #F00 solid;
  overflow-y: scroll;
  }
  div {
    margin: 10px;
  }
  </style>
  </head>
  <body>
  <div>
  <button id="btn_connect">连接</button>
  <button id="btn_close">关闭</button>
  </div>
  <div class="chat" id="chat"></div>
  <div>
  <label for="content">内容:</label>
  <input type="text" id="content" name="content" />
  <button id="btn_send">发送</button>
  </div>
  <script>
  var ws = null;
  var content = document.getElementById('content');
  var chat = document.getElementById('chat');

  function connect() {
    ws = new WebSocket('ws://3.3.3.166:4236');

    ws.onopen = function(e) {
      console.log("connect success!", e, typeof e);
      ws.send(JSON.stringify({'type': 'login', 'data': '823fc765f7cc3b3176f6955c4fded1f6'}));
    };

    ws.onmessage = function(e) {
      console.log(e, e.data, JSON.parse(e.data));
      var o = JSON.parse(e.data)
      if (e.data.length != 0) {
        chat.innerHTML += JSON.stringify(o) + "<br />";
        chat.scrollTop = chat.scrollHeight;
      }
    }

    ws.onclose = function() {
      console.log("connect close!");
    };
  }

  document.getElementById('btn_send').onclick = function() {
    if (content.value.length == 0) {
      alert('请填写用户名或内容!');
      return true;
    }
    ws.send(JSON.stringify({'type': 'chat', 'data': content.value}));
    content.value = "";
    content.focus();
  };

  document.getElementById('btn_close').onclick = function() {
    ws.close();
    chat.innerHTML = "";
  };

  document.getElementById('btn_connect').onclick = function() {
    connect();
  };

  connect();

  </script>
  </body>
</html>
